package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.enums.ArticleStatus;
import com.example.forum.common.enums.ResultCode;
import com.example.forum.common.validation.ValidationUtils;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author hanzishuai
 * @date 2025/4/9 21:11
 * @Description
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    // 用户和板块的操作
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;


    @Override
    @Transactional
    public void create(Article article) {
        if (article == null || article.getUserId() == null
                || article.getBoardId() == null
                || !StringUtils.hasLength(article.getTitle())
                || !StringUtils.hasLength(article.getContent())) {
            log.warn("{}", ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 获取用户信息
        User user = userService.selectById(article.getUserId());

        // 校验用户是否存在
        ValidationUtils.exists(user);
        ValidationUtils.banned(user);

        // 获取板块信息
        Board board = boardService.selectById(article.getBoardId());

        // 判断 board 是否在数据库中存在
        ValidationUtils.banned(board);

        // 设置默认值
        article.setVisitCount(0); // 访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0);  // 点赞数
        article.setDeleteState(ArticleStatus.NOT_DELETE.getStatus());
        article.setState(ArticleStatus.NOT_BANNED.getStatus());
        LocalDateTime date = LocalDateTime.now();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        // 写入数据库
        int articleRow = articleMapper.insertSelective(article);
        if (articleRow <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }


        // 更新用户发帖数
        userService.addOneArticleCountById(user.getId());


        // 更新板块中的贴子数
        boardService.addOneArticleCountById(board.getId());

        log.info("{}，userId = {}，boardId = {}，articleId = {}，发贴成功！", ResultCode.SUCCESS, article.getUserId(),
                article.getBoardId(), article.getId());
//        throw new ApplicationException("测试");
    }

    @Override
    public List<Article> selectAll() {

        List<Article> articles = articleMapper.selectAll();

        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 校验
        ValidationUtils.id(boardId, "板块 Id");

        // 调用 DAO 层，查询板块
        Board board = boardService.selectById(boardId);
        // 校验板块是否存在
        if (board == null) {
            log.warn("{}，boardId = {}", ResultCode.FAILED_BOARD_NOT_EXISTS, boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        List<Article> articles = articleMapper.selectAllByBoardId(boardId);

        return articles;
    }

    /**
     * Created by hanzishuai on 2025/4/10
     *
     * @param id 帖子 Id
     * @return com.example.forum.model.Article
     * @Description 根据帖子 Id 查询帖子详情并更新帖子访问次数
     */
    @Override
    public Article selectDetailById(Long id) {

        // 校验
        ValidationUtils.id(id, "帖子 Id");

        Article article = articleMapper.selectDetailById(id);

        // 校验
        ValidationUtils.banned(article);


        // 更新帖子访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);

        // 保存到数据库中
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        ValidationUtils.singleRowAffected(row);


        // 更新返回对象的访问次数
        article.setVisitCount(article.getVisitCount() + 1);

        // 返回帖子详情
        return article;
    }

    @Override
    public Article selectById(Long id) {
        // 校验
        ValidationUtils.id(id, "帖子 Id");

        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        // 校验 用户 Id
        ValidationUtils.id(userId, "用户 Id");

        // 校验用户信息
        User user = userService.selectById(userId);
        if (user == null) {
            log.warn("{}，user id = {}", ResultCode.FAILED_USER_NOT_EXISTS, userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 调用 DAO
        List<Article> articles = articleMapper.selectByUserId(userId);


        return articles;
    }


    @Override
    public void modify(Long id, String title, String content) {
        // 校验
        ValidationUtils.id(id, "帖子 Id");

        // 要更新的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(LocalDateTime.now());

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        ValidationUtils.singleRowAffected(row);

    }

    /**
     * Created by hanzishuai on 2025/4/12
     *
     * @param id 帖子 id
     * @return void
     * @Description 点赞帖子
     */
    @Override
    public void thumbsUpById(Long id) {
        // 校验
        ValidationUtils.id(id, "帖子 id");


        //  获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);

        // 校验
        ValidationUtils.exists(article);
        ValidationUtils.banned(article);


        // 构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(LocalDateTime.now());

        // 更新数据库

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        ValidationUtils.singleRowAffected(row);

    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        // 校验
        ValidationUtils.id(id, "帖子 Id");


        // 查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);

        // 校验
        ValidationUtils.exists(article);

        // 构建一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState(ArticleStatus.IS_DELETE.getStatus());

        // 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        ValidationUtils.singleRowAffected(row);

        // 更新板块中的帖子数
        boardService.subOneArticleCountById(article.getBoardId());
        // 更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());

        log.info("删除帖子成功，article id = {}，user id = {}", article.getId(), article.getUserId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        // 校验
        ValidationUtils.id(id, "帖子 Id");

        // 获取帖子记录
        Article article = articleMapper.selectByPrimaryKey(id);

        // 校验
        ValidationUtils.exists(article);
        ValidationUtils.banned(article);

        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(LocalDateTime.now());

        // 执行更新操作
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        ValidationUtils.singleRowAffected(row);
    }

    @Override
    public void subOneReplyCountById(Long id) {
        // 校验
        ValidationUtils.id(id, "帖子 Id");

        // 获取帖子记录
        Article article = articleMapper.selectByPrimaryKey(id);

        // 校验
        ValidationUtils.exists(article);
        ValidationUtils.banned(article);

        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount() - 1);
        updateArticle.setUpdateTime(LocalDateTime.now());

        // 执行更新操作
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        ValidationUtils.singleRowAffected(row);
    }

    @Override
    public List<Article> search(String content) {
        // 校验
        if (content == null) {
            log.warn("输入的内容为空");
            throw new ApplicationException(AppResult.failed("输入的内容为空"));
        }

        // 调用 DAO
        String keyword = "%" + content.replace("%", "\\%")
                .replace("_", "\\_") + "%";

        List<Article> articleList = articleMapper.search(keyword);

        return articleList;
    }

    @Override
    public void updateByPrimaryKeySelective(Article article) {
        if (article == null || article.getId() == null || article.getId() <= 0) {
            log.warn("{}", ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = articleMapper.updateByPrimaryKeySelective(article);

        ValidationUtils.singleRowAffected(row);
    }


}

























